package org.seckill.service;

import java.util.Date;
import java.util.List;


import org.seckill.dao.SeckillDao;
import org.seckill.dao.SuccessKilledDao;
import org.seckill.dto.Exposer;
import org.seckill.dto.SeckillExecution;
import org.seckill.entity.Seckill;
import org.seckill.entity.SuccessKilled;
import org.seckill.enums.SeckillEnum;
import org.seckill.exception.RepeatKillException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
@Service
public class SeckillServiceImpl implements SeckillService {

	@Autowired
	private SeckillDao seckillDao;
	@Autowired
	private SuccessKilledDao successkilledDao;
	
	private final String slat = "jfh][]854*&()&)%&^%&$jhdgHGFRHOIHOH";
	@Override
	public List<Seckill> getSeckillList() {
		return seckillDao.queryAll(0,4);
	}

	@Override
	public Seckill getById(long id) {
		return seckillDao.queryById(id);
	}

	@Override
	public Exposer exportSeckillUrl(long seckillId) {
		Seckill seckill = seckillDao.queryById(seckillId);
		if (seckill==null) {
			return new Exposer(false, seckillId);
		}
		Date startTime = seckill.getStartTime();
		Date endTime = seckill.getEndTime();
		Date nowTime = new Date();
		
		if (nowTime.getTime()<startTime.getTime()
			||nowTime.getTime()>endTime.getTime()) {
			return new Exposer(false,seckillId,nowTime.getTime(), startTime.getTime(), endTime.getTime());
		}
		String md5 = getMD5(seckillId);
		return new Exposer(true, md5, seckillId);
	}
	
	private String getMD5(long seckillId){
		String base = seckillId + slat;
		String md5 = DigestUtils.md5DigestAsHex(base.getBytes());
		return md5;
	}

	@Override
	@Transactional
	public SeckillExecution executeSeckill(long seckillId, long userPhone, String md5) throws RepeatKillException {
		if(md5==null || !md5.equals(getMD5(seckillId))){
			throw new RepeatKillException("seckill data rewrite");
		}
		try {
			Date nowTime = new Date();
			int updateCount = seckillDao.reduceNumber(seckillId, nowTime);
			if(updateCount<=0){
				throw new RepeatKillException("seckill is closed");
			}else{
				int insertCount = successkilledDao.insertSuccessKilled(seckillId, userPhone);
				if (insertCount<=0) {
					throw new RepeatKillException("seckill repated");
				}else{
					SuccessKilled successKilled =  successkilledDao.queryByIdWithSeckill(seckillId,userPhone);
					return new SeckillExecution(seckillId,SeckillEnum.SUCCESS, successKilled);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RepeatKillException("seckill insert error");
		}
	}

}
